package com.smartsystem.modules.system.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.smartsystem.common.controller.BaseController;
import com.smartsystem.common.utils.Result;
import com.smartsystem.modules.system.dto.SysUserDTO;
import com.smartsystem.modules.system.dto.SysUserQueryDTO;
import com.smartsystem.modules.system.service.SysUserService;
import com.smartsystem.modules.system.vo.SysUserVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;

/**
 * 用户管理控制器
 */
@RestController
@RequestMapping("/api/v1/system/users")
@Tag(name = "用户管理", description = "用户信息的增删改查等操作")
@Validated
public class SysUserController extends BaseController {

    @Resource
    private SysUserService sysUserService;

    /**
     * 分页查询用户列表
     */
    @GetMapping("/page")
    @Operation(summary = "分页查询用户列表", description = "根据条件分页查询用户信息")
    public Result<IPage<SysUserVO>> getUserPage(@Parameter(description = "查询条件") SysUserQueryDTO queryDTO) {
        IPage<SysUserVO> page = sysUserService.getUserPage(queryDTO);
        return Result.success(page);
    }

    /**
     * 根据ID获取用户详情
     */
    @GetMapping("/{id}")
    @Operation(summary = "获取用户详情", description = "根据用户ID获取用户详细信息")
    public Result<SysUserVO> getUserById(
            @Parameter(description = "用户ID", required = true)
            @PathVariable @NotNull(message = "用户ID不能为空") Long id) {
        SysUserVO userVO = sysUserService.getUserById(id);
        return Result.success(userVO);
    }

    /**
     * 创建用户
     */
    @PostMapping
    @Operation(summary = "创建用户", description = "创建新的用户信息")
    public Result<Long> createUser(
            @Parameter(description = "用户信息", required = true)
            @RequestBody @Valid SysUserDTO userDTO) {
        
        // 检查用户名是否存在
        if (sysUserService.checkUsernameExists(userDTO.getUsername(), null)) {
            return Result.fail("用户名已存在");
        }
        
        // 检查手机号是否存在
        if (userDTO.getPhone() != null && sysUserService.checkPhoneExists(userDTO.getPhone(), null)) {
            return Result.fail("手机号已存在");
        }
        
        // 检查邮箱是否存在
        if (userDTO.getEmail() != null && sysUserService.checkEmailExists(userDTO.getEmail(), null)) {
            return Result.fail("邮箱已存在");
        }
        
        Long userId = sysUserService.createUser(userDTO);
        return Result.success(userId, "用户创建成功");
    }

    /**
     * 更新用户
     */
    @PutMapping("/{id}")
    @Operation(summary = "更新用户", description = "更新用户信息")
    public Result<Boolean> updateUser(
            @Parameter(description = "用户ID", required = true)
            @PathVariable @NotNull(message = "用户ID不能为空") Long id,
            @Parameter(description = "用户信息", required = true)
            @RequestBody @Valid SysUserDTO userDTO) {
        
        userDTO.setId(id);
        
        // 检查用户名是否存在
        if (sysUserService.checkUsernameExists(userDTO.getUsername(), id)) {
            return Result.fail("用户名已存在");
        }
        
        // 检查手机号是否存在
        if (userDTO.getPhone() != null && sysUserService.checkPhoneExists(userDTO.getPhone(), id)) {
            return Result.fail("手机号已存在");
        }
        
        // 检查邮箱是否存在
        if (userDTO.getEmail() != null && sysUserService.checkEmailExists(userDTO.getEmail(), id)) {
            return Result.fail("邮箱已存在");
        }
        
        Boolean result = sysUserService.updateUser(userDTO);
        return Result.success(result, "用户更新成功");
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/{id}")
    @Operation(summary = "删除用户", description = "根据ID删除用户")
    public Result<Boolean> deleteUser(
            @Parameter(description = "用户ID", required = true)
            @PathVariable @NotNull(message = "用户ID不能为空") Long id) {
        Boolean result = sysUserService.deleteUser(id);
        return Result.success(result, "用户删除成功");
    }

    /**
     * 批量删除用户
     */
    @DeleteMapping("/batch")
    @Operation(summary = "批量删除用户", description = "根据ID列表批量删除用户")
    public Result<Boolean> deleteUsers(
            @Parameter(description = "用户ID列表", required = true)
            @RequestBody @NotEmpty(message = "用户ID列表不能为空") List<Long> ids) {
        Boolean result = sysUserService.deleteUsers(ids);
        return Result.success(result, "用户批量删除成功");
    }

    /**
     * 重置用户密码
     */
    @PutMapping("/{id}/reset-password")
    @Operation(summary = "重置用户密码", description = "重置指定用户的密码")
    public Result<Boolean> resetPassword(
            @Parameter(description = "用户ID", required = true)
            @PathVariable @NotNull(message = "用户ID不能为空") Long id,
            @Parameter(description = "新密码信息", required = true)
            @RequestBody Map<String, String> passwordMap) {
        
        String newPassword = passwordMap.get("newPassword");
        if (newPassword == null || newPassword.trim().isEmpty()) {
            return Result.fail("新密码不能为空");
        }
        
        if (newPassword.length() < 6 || newPassword.length() > 20) {
            return Result.fail("密码长度必须在6-20个字符之间");
        }
        
        Boolean result = sysUserService.resetPassword(id, newPassword);
        return Result.success(result, "密码重置成功");
    }

    /**
     * 修改用户状态
     */
    @PutMapping("/{id}/status")
    @Operation(summary = "修改用户状态", description = "启用或禁用用户")
    public Result<Boolean> updateStatus(
            @Parameter(description = "用户ID", required = true)
            @PathVariable @NotNull(message = "用户ID不能为空") Long id,
            @Parameter(description = "状态信息", required = true)
            @RequestBody Map<String, Integer> statusMap) {
        
        Integer status = statusMap.get("status");
        if (status == null || (status != 0 && status != 1)) {
            return Result.fail("状态值必须为0或1");
        }
        
        Boolean result = sysUserService.updateStatus(id, status);
        String message = status == 1 ? "用户启用成功" : "用户禁用成功";
        return Result.success(result, message);
    }

    /**
     * 检查用户名是否存在
     */
    @GetMapping("/check-username")
    @Operation(summary = "检查用户名", description = "检查用户名是否已存在")
    public Result<Boolean> checkUsername(
            @Parameter(description = "用户名", required = true)
            @RequestParam String username,
            @Parameter(description = "排除的用户ID")
            @RequestParam(required = false) Long excludeId) {
        Boolean exists = sysUserService.checkUsernameExists(username, excludeId);
        return Result.success(!exists, exists ? "用户名已存在" : "用户名可用");
    }

    /**
     * 检查手机号是否存在
     */
    @GetMapping("/check-phone")
    @Operation(summary = "检查手机号", description = "检查手机号是否已存在")
    public Result<Boolean> checkPhone(
            @Parameter(description = "手机号", required = true)
            @RequestParam String phone,
            @Parameter(description = "排除的用户ID")
            @RequestParam(required = false) Long excludeId) {
        Boolean exists = sysUserService.checkPhoneExists(phone, excludeId);
        return Result.success(!exists, exists ? "手机号已存在" : "手机号可用");
    }

    /**
     * 检查邮箱是否存在
     */
    @GetMapping("/check-email")
    @Operation(summary = "检查邮箱", description = "检查邮箱是否已存在")
    public Result<Boolean> checkEmail(
            @Parameter(description = "邮箱", required = true)
            @RequestParam String email,
            @Parameter(description = "排除的用户ID")
            @RequestParam(required = false) Long excludeId) {
        Boolean exists = sysUserService.checkEmailExists(email, excludeId);
        return Result.success(!exists, exists ? "邮箱已存在" : "邮箱可用");
    }
}